<template>
  <view class="content">
    <view class="content-txt">
      <view v-for="(item, index) in chatList" :key="index">
        <Question
          v-if="item.type === 'question'"
          :chatRecord="item"
          :index="index"
        ></Question>
        <Answer
          v-if="item.type === 'answer'"
          :chatRecord="item"
          :index="index"
        ></Answer>
      </view>
    </view>
    <view class="content-input">
      <input
        class="input-style"
        placeholder="请输入问题,按enter触发"
        v-model="questionTxt"
        @keydown.enter="getChatData"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Question from "./Question.vue";
import Answer from "./Answer.vue";

const questionTxt = ref("");
const chatList: any = ref([]);

async function getChatData() {
  chatList.value.push({
    problem_text: questionTxt.value,
    type: "question",
  });

  // 等待200秒表示思考中
  await new Promise((resolve) => setTimeout(resolve, 100));
  chatList.value.push({
    problem_text: "",
    type: "answer",
  });

  const resp: any = await fetch("/api/gpt-stream", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });

  const reader = resp.body.getReader();
  const decoder = new TextDecoder();
  while (1) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    chatList.value[chatList.value.length - 1].answer_text +=
      decoder.decode(value);
  }
}
</script>

<style>
.content {
  position: relative;

  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}
.content-txt {
  /* background-color: #f5f5f5; */
  position: relative;

  width: 100%;
  height: 400px;
  overflow: auto;
  box-sizing: border-box;
  padding: 10px;
}
.content-input {
  position: relative;
  margin-top: 10px;
  font-size: 14px;
}
.input-style {
  border: 1px solid #e1e1e1;
  height: 36px;
  border-radius: 4px;
  padding: 0 14px;
}
</style>
